In Python, the Boolean data type (often shortened to "Bool") is fundamental for representing the concepts of True and False. Boolean values are central to decision-making and conditional logic in programming.
Key Characteristics
Two Possible Values:
⯁ True
⯁ False
Important: Note that these keywords are case-sensitive.
Result of Comparisons:
⯁ Greater than (>), less than (<), equal to (==), not equal to (!=)
⯁ Example: 10 > 5 results in the Boolean value True.
Conditional Logic:
⯁ if and else statements use Boolean expressions to execute different code blocks depending on the condition.
⯁ while loops use Boolean conditions to determine how long to continue running.
Creating Boolean Variables:
Creating boolean variables | boolean type example
#You directly assign Boolean values to variables
is_valid = True
has_error = False
print(is_valid)
print(type(has_error))
print(type(True))
Output
True
<class 'bool'>
<class 'bool'>
Operations on Booleans
Python supports logical operators for combining and manipulating Boolean values:
✦
not (Negation): Inverts the Boolean value. not True results in False.
✦
and (Conjunction): Returns True only if both operands are True. Otherwise, it returns False.
✦
or (Disjunction): Returns True if at least one of the operands is True. It returns False only if both operands are False.
Example:
Boolean in logical operators example in python
is_student = True
is_registered = False
can_attend_class = is_student and is_registered
print(can_attend_class)
can_attend_class = is_student or is_registered
print(can_attend_class)
Output
False
True
Truthiness of Non-Boolean Values
In conditional contexts, most non-Boolean values in Python have an inherent "truthiness" or "falsiness":
Falsy values:
⯁ None
⯁ False
⯁ Zero of any numeric type (0, 0.0)
⯁ Empty sequences and collections (e.g., "", [], {})
Truthy values: Most other values are considered "Truthy".